package com.GainLoop;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.jar.JarEntry;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;

import com.GainLoop.Api.ApiResponseObject;
import com.GainLoop.Api.Users;
import com.GainLoop.Api.Entity.User;
import com.GainLoop.Api.Entity.User.GENDER;
import com.GainLoop.Data.Registry;
import com.facebook.android.*;
//import com.facebook.android.R;
import com.facebook.android.Facebook.*;


public class Home extends TabActivity {
	public static final String APP_ID = "184501141565634";
    
	Facebook facebook = new Facebook(APP_ID);
    private AsyncFacebookRunner mAsyncRunner;
    
    private Button getButton;
    private Button giveButton;
    private Button GainListButton;
    private User user;
   // private Button mDeleteButton;
    
    public void onCreate(Bundle savedInstanceState) {
    	Log.v("test","1");
        super.onCreate(savedInstanceState);
        Log.v("test","1.5");
        setContentView(R.layout.home);
        Log.v("test","2");
        //mAsyncRunner = new AsyncFacebookRunner(facebook);
       
//        giveButton = (Button) findViewById(R.id.giveButton);
//        getButton = (Button) findViewById(R.id.getButton);
//        
//        GainListButton = (Button) findViewById(R.id.GainListButton);
//        
//        giveButton.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {
//            	Intent intent=new Intent(Home.this,GiveGain.class);
//            	Home.this.startActivity(intent);
//            }
//        });
//        getButton.setOnClickListener(new View.OnClickListener() {
//        	public void onClick(View v) {
//            	Intent intent=new Intent(Home.this,GetGain.class);
//            	Home.this.startActivity(intent);
//            }
//        });
//        
//        GainListButton.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {
//            	Intent intent=new Intent(Home.this,GainPage.class);
//            	intent.putExtra(GainPage.GAIN_ID, new Long(4));
//            	Home.this.startActivity(intent);
//            }
//        });
        
     
        
        facebook.authorize(this,new String[] { "email"}, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
				
            	String response = null;
            	String name = null;
            	String fbId = null;
            	String link = null;
            	JSONObject hometownJson = null;
            	String hometown = null;
            	JSONObject locationJson = null;
            	String locationName = null;
            	String locationId = null;
            	String location = null;
            	String birthday = null;
            	String gender = null;
            	String local = null;
            	String email = null;
            	try {
            		//Get the user profile info to a string object.
            		response = facebook.request("me");
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				JSONObject json;
				try {
					//it is a JSON object , so we need to parse it to take what we need...
					json = Util.parseJson(response);
					name = json.getString("name");
					fbId = json.getString("id");
					link = json.getString("link");
					email = json.getString("email");
					hometownJson = Util.parseJson(json.getString("hometown"));
					hometown = hometownJson.getString("name");
					location = json.getString("location");
					birthday = json.getString("birthday");
					locationJson = Util.parseJson(json.getString("location"));
					locationName = hometownJson.getString("name");
					locationId = hometownJson.getString("id");
					gender = hometownJson.getString("gender");
					local = hometownJson.getString("local");
					
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (FacebookError e) {
					e.printStackTrace();
				}
               
                
				/*Toast toast = Toast.makeText(Home.this, name, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, fbId, Toast.LENGTH_LONG);
				toast.show();
				toast = Toast.makeText(Home.this, link, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, hometown, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, "https://graph.facebook.com/"+fbId+"/picture?type=large", Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, locationName, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, locationId, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, birthday, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, gender, Toast.LENGTH_LONG);
				//toast.show();
				toast = Toast.makeText(Home.this, local, Toast.LENGTH_LONG);
				//toast.show();
				//toast = Toast.makeText(Home.this, email, Toast.LENGTH_LONG);
				//toast.show();
				 */				
				Users users = new Users();
				
//				Toast toast = Toast.makeText(Home.this, name, Toast.LENGTH_LONG);
//				toast.show();
//				toast = Toast.makeText(Home.this, fbId, Toast.LENGTH_LONG);
//				toast.show();
//				toast = Toast.makeText(Home.this, locationName, Toast.LENGTH_LONG);
//				toast.show();
				long fbIdLong = Long.parseLong(fbId);
				//check if user is already in server DB...
				ApiResponseObject<User> resp = null;
				try {
					resp = users.getByFbId(fbIdLong);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONRPCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				User user = null;
				user=resp.getData();
				Log.v("user",user.toString());
				
				if(resp.getReturnCode()==0 && user!=null){
					Log.v("user", "Already in DB!");
					Registry.SetUser(user);
					return;
				}
				else{
					Log.v("user", "not in DB!");
				}
				//here i will add the user to the server DB.
				User newUser = new User();
				newUser.setFbId(fbIdLong);
				newUser.setEmail(email);
				newUser.setName(name);
				if(gender==null){
					newUser.setGender(GENDER.UNKNOWN);
				}
				else{
					Log.v("gender",gender);
	
					if(gender.compareTo("MALE")==0){
						newUser.setGender(GENDER.MALE);
					}
					else{
						newUser.setGender(GENDER.FEMALE);
					}
				}
				if (birthday!=null)
					newUser.setBirthday(new Date(birthday));
				
				newUser.setLocale(local);
				if (locationId!=null)
					newUser.setLocationId(Long.parseLong(locationId));
				newUser.setLocationName(locationName);
				
				try {
					ApiResponseObject<User> res = users.create(newUser);
					if(res.getReturnCode() == 0) {
						newUser = res.getData();
						Registry.SetUser(newUser);
					} else {
						if(res.getReturnCode() == -10 || res.getReturnCode() == -11){
							
							throw new RuntimeException("user already created");
						}
						else
							throw new RuntimeException("unknown error code: " + res.getReturnCode());
					}
				} catch (JSONException e2) {
					// TODO handle this case 
					e2.printStackTrace();
				} catch (JSONRPCException e2) {
					// TODO handle this case
					e2.printStackTrace();
				}
				
				
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
        });
        
        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost 
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, TopGains.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("Top Wishes").setIndicator("Top Wishes",
                          res.getDrawable(R.drawable.ic_tab_artists))
                      .setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, RecentGains.class);
        spec = tabHost.newTabSpec("Recent Wishes").setIndicator("Recent Wishes",
                          res.getDrawable(R.drawable.ic_tab_artists))
                      .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(1);

    }
    public boolean onCreateOptionsMenu(Menu menu) {
    	Log.v("home", "inflating menu ..");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        menu.setGroupVisible(R.id.group1, false);
        menu.setGroupVisible(R.id.group2, false);
        menu.setGroupVisible(R.id.group3, false);
        
        menu.setGroupVisible(R.id.groupHome, false);
        
        Log.v("home", "disable menus ..");
        
        return true;
    }
    public boolean onOptionsItemSelected (MenuItem item){
    	Toast toast;
    	Intent intent;
		 switch (item.getItemId()) {
		    case R.id.menu_profile_button:
		    	intent=new Intent(Home.this,UserPage.class);
            	Home.this.startActivity(intent);
		        return true;
		    case R.id.help_button:
		    	toast = Toast.makeText(Home.this,"help", Toast.LENGTH_LONG);
				toast.show();
		        return true; 
		    case R.id.menu_search_button:
		    	intent=new Intent(Home.this,GainSearch.class);
            	Home.this.startActivity(intent);
		        return true;
		    case R.id.menu_new_gain_button:
		    	intent=new Intent(Home.this,AddRequest.class);
            	Home.this.startActivity(intent);
		        return true;   
		        
		    default:
		        return super.onOptionsItemSelected(item);
		    }
		
    }
   
    /*public void showActivity(View view,Class activityClass) {     
      	Intent intent=new Intent(view.getContext(),Home.class);
      	view.getContext().startActivity(intent);
      }*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
}